﻿import com.dinmax.flash.utilities.timer.*

class Timer {
	
	private static var DURATION_DEFAULT:Number = 3000;
	private var nDuration:Number;
	private var nStartTimer:Number;
	private var dummyClip:MovieClip;
	private var aListeners:Array; // de TimerListener
	
	function Timer() {
		this.resetListeners();
		this.setDuration(Timer.DURATION_DEFAULT);
	};
	
	public function getDuration():Number {
		return this.nDuration;
	};
	
	public function setDuration(duration:Number):Void {
		this.nDuration = duration;
		return;
	};
	
	public function addListener(listener:TimerListener):Void {
		this.removeListener(listener);
		this.aListeners.push(listener);
		return;
	};
	public function removeListener(listener:TimerListener):Void {
		for(var i:Number = 0; i < this.aListeners.length; i++){
			if(this.aListeners[i] == listener){
				this.aListeners.splice(i, 1);
			};
		};
		return;
	};
	public function resetListeners():Void {
		this.aListeners = new Array();
		return;
	};
	
	public function startTimer():Void {
		this.nStartTimer = getTimer();
		removeMovieClip(this.dummyClip);
		this.dummyClip = _root.createEmptyMovieClip("mcDummyClip"+_root.getNextHighestDepth(), _root.getNextHighestDepth());
		this.dummyClip.timer = this;
		this.dummyClip.nTimer = this.nStartTimer;
		this.dummyClip.onEnterFrame = function():Void {
			var nDif:Number = getTimer() - this.nTimer;
			if(nDif >= this.timer.getDuration()){
				delete this.onEnterFrame;
				this.timer.timeOut();
			}
			return;
		};
		return;
	};
		
	public function resetTimer():Void {
		this.nStartTimer = getTimer();
		return;
	};
	
	private function timeOut():Void {
		for(var i:Number = 0; i < this.aListeners.length; i++){
			var list:TimerListener = this.aListeners[i];
			list.timeOut();
		};
		return;
	};
	
} // fin de clase